// 环境变量
import 'xl-ts-plugins/env'

import express from 'express'
import path from 'path'
import fs from 'fs'
// 解析 body
import bodyParser from 'body-parser'
// 上传文件
import multer from 'multer'
// 设置
import { PORT, RESOURCES_PATH, UPLOAD_PREFIX, IMAGE_SUFFIXS, IMAGE_TYPE } from './config'

import { getSuffix, mkdirCheckExists, md5, saveExtraImage, getFileName } from './utils'

// 生成保存路径
mkdirCheckExists(RESOURCES_PATH)

const app = express()

// 支持跨域
app.all('*', function (req, res, next) {
  // 设置允许跨域的域名，*代表允许任意域名跨域
  res.header('Access-Control-Allow-Origin', '*')
  // 允许的header类型
  res.header('Access-Control-Allow-Headers', 'content-type')
  // 跨域允许的请求方式
  res.header('Access-Control-Allow-Methods', 'DELETE,PUT,POST,GET,OPTIONS')
  // 让options尝试请求快速结束
  if (req.method.toLowerCase() == 'options')
    res.send("200")
  else
    next()
})

// 解析 body
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

let SaveFileName = ''
let SaveFileSuffix = ''

// 上传接口
app.post(
  '/upload',
  (req, res, next) => {
    SaveFileName = ''
    SaveFileSuffix = ''
    next()
  },
  multer({
    storage: multer.diskStorage({
      destination: function(req, file, cb) {
        const buildDir = RESOURCES_PATH
        mkdirCheckExists(buildDir)
        cb(null, buildDir)
      },
      filename: function(req, file, cb) {
        const suffix = getSuffix(file.originalname)
        SaveFileSuffix = suffix
        const fileName = md5(Date.now() + '_' + file.fieldname)
        SaveFileName = fileName
        cb(null, fileName + '.' + suffix)
      },
    }),
  }).single('file'),
  (req, res) => {
    const filename = SaveFileName + '.' + SaveFileSuffix

    res.json({
      code: 200,
      data: path.posix.join(UPLOAD_PREFIX, Buffer.from(filename).toString('base64')),
      msg: '上传成功'
    })

    // 如果是图片生成 水印图 和 缩略图
    if (IMAGE_SUFFIXS.includes(SaveFileSuffix)) {
      saveExtraImage(filename)
    } 
  }
)

// 获取
app.get('/files/:filename', (req, res) => {
  const filename = Buffer.from(req.params.filename, 'base64').toString()
  const suffix = getSuffix(filename)
  const isImage = IMAGE_SUFFIXS.includes(suffix)
  const type = !req.query.type || !Object.keys(IMAGE_TYPE).map(key => IMAGE_TYPE[key]).includes(req.query.type) ? IMAGE_TYPE.ORIGINAL : req.query.type
  let filePath = path.join(RESOURCES_PATH, filename)

  if (isImage && type !== IMAGE_TYPE.ORIGINAL) {
    filePath = path.join(RESOURCES_PATH, getFileName(filename) + `_${type}.` + suffix)
  }

  // 判断文件是否存在
  if (fs.existsSync(filePath)) {
    const crs = fs.createReadStream(filePath)

    crs.on('data', chunk => {
      res.write(chunk)
    })

    crs.on('end', () => {
      res.status(200)
      res.end()
    })
  } else {
    res.sendStatus(404)
  }
})


app.listen(PORT, () => {
  console.log(`Server running at port: ${PORT}`)
})

